#!/usr/bin/env python
# coding=utf-8

from vavava.httpclient import HttpClient
from vavava.util import LogAdapter,initlog,reg_helper
import logging,os,time,threading

def _get_time_string():
    return time.strftime("%Y%m%d%H%M%S",time.localtime())

class _file_downloader:
    def __init__(self,out_path="./"):
        self.__out_path = os.path.abspath(out_path)
        self.__file_name = None
        self.__file = self.__int_filename()
        self.__mutex = threading.Lock()
        self.__is_recoding = True
        self.__stop_time = time.clock() + 1800.0
    def __int_filename(self):
        if not self.__file_name or not self.__file:
            self.__file_name = _get_time_string() + ".flv"
            self.__file_name = os.path.join(self.__out_path, self.__file_name)
            return open(self.__file_name, "wb")
        return self.__file
    def stop_recode(self):
        self.__mutex.acquire()
        self.__is_recoding = False
        self.__mutex.release()
    def write(self,data):
        if self.__file:
            self.__file.write(data)
            self.__mutex.acquire()
            flag = self.__is_recoding
            self.__mutex.release()
            if flag and (self.__stop_time > time.clock()):
                return True
            else:
                return False
    def __del__(self):
        if self.__file:
            self.__file.close()

class Spider:
    __charset = r"utf-8"
    __flv_location = r"http://58.22.105.114:1755/30065NfWL5jwG------gk5c0YYr5c05c0---5ckRXg04lXklRRb0UUkH-mbbUUmk0RU4USewTejjjTm7ijN--5N5mfWL5j5N.I.o5j0XU5c00HUk5c-5cL5cR5c0---5c-5N5m.I.o5j5NpoF5j0k0J0gJXRJkR5lH-H-5c00RJ0-HJkRXJk-5lH-H-5cH-H-5N5mpoF5j5NK8z5jvBovIp5lRHH5cdfdK5lk0HJkJ0RrJ0X05lH-5c.sQ.o5lBsA.5cds5lDCF5cfW5l0YYr5csA5l0RXH-Rk0Xg5cBp5lrR-g5cZK5lXHJkkJ0-XJ00X5cvf5l0-kg5N5mK8z5j5NxdoB5jSewTTu5w0kX-Rr--r0R-5c0kXJRrJrJ0R-5N5mxdoB5j/?sw_sigh=0b4ef67dbf"
    def __init__(self,log=None):
        self.__http = HttpClient()
        self.__http.header_refer_ = "http://v.ifeng.com/include/ifengLivePlayer_v1.40.4.swf"
        self.__http.header_user_agent_ = r"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"
        self.__http.AddHeader({"x-flash-version":"11,5,502,146"})
        self.__http.AddHeader({"Accept-Language":"zh-CN"})
        self.__http.AddHeader({"Accept":"*/*"})
        self.__http.AddHeader({"Proxy-Connection":"Keep-Alive"})
        self.__log = LogAdapter(log)
        self.file_downloader = None
    def start_recode(self):
        self.file_downloader = _file_downloader()
        while True:
            try:
                self.__http.Get( Spider.__flv_location,callback=self.file_downloader )
                self.__log.info("stop recode(normally)")
                break
            except Exception as e:
                self.__log.exception(e)
    def stop_recode(self):
        if self.file_downloader:
            self.file_downloader.stop_recode()


# test #######################################################################
def test(path):
    logger = initlog(logfile="test.log",level=logging.DEBUG)
    test = Spider( logger )
    try:
        logger.info("start recoding .................")
        test.start_recode()
        logger.info("stop recoding ..1...............")
    except KeyboardInterrupt:
        test.stop_recode()
        logger.info("stop recoding ..2...............")

if __name__ == "__main__":
    import sys
    path = "./"
    if len(sys.argv) > 1:
        path = sys.argv[1]
    test(path)



# test #######################################################################
















location_1 = r'http://live.ifeng.com/liveAllocation.do?cid=270DE943-3CDF-45E1-8445-9403F93E80C4'
"""
HTTP/1.1 200 OK
Date: Sun, 13 Jan 2013 00:42:18 CST
Expires: Fri, 13 Jan 2023 00:42:18 CST
Last-Modified: Sun, 13 Jan 2013 00:42:18 CST
Content-Type: text/html; charset=utf-8
Server: HttpServer ($Revision: 555855 $ $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $)
Cache-Control: max-age=315360000
Content-Length: 277

{"link":"http://biz.vsdn.tv380.com/playlive.php?5B63686E5D445830303030303034327C313636397C317C313030307CE587A4E587B0E4B8ADE696872846297C72746D707C666C765B2F63686E5D5B74735D307C687474705B2F74735DVSDNSOOONERCOM00|js","cid":"270DE943-3CDF-45E1-8445-9403F93E80C4","cdnid":"Sooner"}
"""

location_2 = r'http://biz.vsdn.tv380.com/playlive.php?uuid=5B63686E5D445830303030303034327C313636397C317C313030307CE587A4E587B0E4B8ADE696872846297C72746D707C666C765B2F63686E5D5B74735D307C687474705B2F74735DVSDNSOOONERCOM00&swax_rt=js&ifenai=ifeng&ifenfg=&ifents=1357989259&ifenv=1&ifensg=c19a363eaa&ifenuserid='
"""
GET http://biz.vsdn.tv380.com/playlive.php?uuid=5B63686E5D445830303030303034327C313636397C317C313030307CE587A4E587B0E4B8ADE696872846297C72746D707C666C765B2F63686E5D5B74735D307C687474705B2F74735DVSDNSOOONERCOM00&swax_rt=js&ifenai=ifeng&ifenfg=&ifents=1358009243&ifenv=1&ifensg=114b17474c&ifenuserid= HTTP/1.1
Accept: */*
Accept-Language: zh-CN
Referer: http://v.ifeng.com/include/ifengLivePlayer_v1.40.4.swf
x-flash-version: 11,5,502,146
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
Host: biz.vsdn.tv380.com
Connection: Keep-Alive

HTTP/1.1 200 OK
Server: nginx
Date: Sat, 12 Jan 2013 16:42:18 GMT
Content-Type: text/html; charset=utf-8
Connection: close
Expires: Mon, 26 Jul 1997 05:00:00 GMT
Last-Modified: Sat, 12 Jan 2013 16:42:18 GMT
Cache-Control: no-store, no-cache, must-revalidate
Cache-Control: post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 468

var playurl="rtmp://58.22.105.114:1755/30175NfWL5jwG------gk5c0YYr5c05c0---5ckRXg04lXklRRb0UUkH-mbbUUmk0RU4USewTejjjTm7ijN--5N5mfWL5j5N.I.o5j0XU5c00HUk5c-5cL5cR5c0---5c-5N5m.I.o5j5NpoF5j0k0J0gJXRJkR5lH-H-5c00RJ0-HJkRXJk-5lH-H-5cH-H-5N5mpoF5j5NK8z5jvBovIp5lRHH5cdfdK5lk0HJkJ0RrJ0X05lH-5c.sQ.o5lBsA.5cds5lDCF5cfW5l0YYr5csA5l0RXH-Xk0RH5cBp5lgHkr5cZK5lXHJkkJ0-XJ00X5cvf5l0-kg5N5mK8z5j5NxdoB5jSewTTu5w0kX-Rr--r0R-5c0kXJRrJrJ0R-5N5mxdoB5j/?sw_sigh=e628077a3d";goOn(playurl);
"""


















